<template>
  <div class="charge-container" id="chargeContainer">
    <div class="charge">
      <!--<h1 class="charge-title">记账凭证</h1>-->
      <div class="charge-header">
        <div>
          凭证字
          <a-select style="width: 80px;" v-model:value="voucher.word">
            <a-select-option v-for="item in wordList" :key="item.name" :value="item.name">{{ item.name }}</a-select-option>
          </a-select>

        </div>

        <div>
          凭证号
          <a-input type="number" style="width: 80px;" min="1" v-model:value="voucher.no"></a-input>
        </div>

        <div>
          日期
          <a-date-picker style="width: 145px;" v-model:value="voucher.date" />
        </div>

        <div style="font-size: 24px;">记账凭证</div>

        <div style="float: right;position: relative;">
          附单据
          <a-input type="number" style="width: 80px;" min="0" v-model:value="voucher.bill"></a-input>
          张
          <span class="anticon anticon-info-circle" style="font-size: 18px; margin-left: 30px; cursor: pointer;" @mouseenter="showTipBox = true" @mouseleave="showTipBox = false"></span>
          <div class="tip-box" v-show="showTipBox">
            <table class="tip-box-table" border="1">
              <tr style="background-color: #f5f4f4;">
                <td>操作</td>
                <td>快捷键</td>
              </tr>
              <tr>
                <td>选择列表</td>
                <td>F7</td>
              </tr>
              <tr>
                <td>自动平衡</td>
                <td>=</td>
              </tr>
              <tr>
                <td>新增</td>
                <td>F4</td>
              </tr>
              <tr>
                <td>保存</td>
                <td>Ctrl+S</td>
              </tr>
              <tr>
                <td>保存并审核</td>
                <td>F10</td>
              </tr>
              <tr>
                <td>保存并新增</td>
                <td>F11</td>
              </tr>
              <tr>
                <td>复制上一行</td>
                <td>//</td>
              </tr>
              <tr>
                <td>复制上一行摘要</td>
                <td>..</td>
              </tr>
              <tr>
                <td>金额自动切换借贷方</td>
                <td>空格键</td>
              </tr>
              <tr>
                <td>单据头与分录快速切换</td>
                <td>Tab</td>
              </tr>
            </table>
          </div>
        </div>
      </div>
      <table class="charge-table" border="1">
        <tr>
          <td width="6%">行次</td>
          <td :width="isAuxiliary ? '14%' : '22%'">摘要</td>
          <td :width="isAuxiliary ? '15%' : '22%'">会计科目</td>
          <td width="14%" v-if="isAuxiliary">辅助核算</td>
          <td width="50%">
            <table style="height: 50px;">
              <tr style="border-bottom: 1px solid #bab9b9;">
                <td width="50%" style="border-right: 1px solid #bab9b9;">借方金额</td>
                <td width="50%">贷方金额</td>
              </tr>
              <tr>
                <td style="border-right: 1px solid #bab9b9;">
                  <table class="debtor-lender-table" style="height: 100%;">
                    <tr>
                      <td>亿</td>
                      <td>千</td>
                      <td>百</td>
                      <td>十</td>
                      <td>万</td>
                      <td>千</td>
                      <td>百</td>
                      <td>十</td>
                      <td>元</td>
                      <td>角</td>
                      <td>分</td>
                    </tr>
                  </table>
                </td>
                <td>
                  <table class="debtor-lender-table" style="height: 100%;">
                    <tr>
                      <td>亿</td>
                      <td>千</td>
                      <td>百</td>
                      <td>十</td>
                      <td>万</td>
                      <td>千</td>
                      <td>百</td>
                      <td>十</td>
                      <td>元</td>
                      <td>角</td>
                      <td>分</td>
                    </tr>
                  </table>
                </td>
              </tr>
            </table>
          </td>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>
            {{ index + 1 }}
          </td>
          <td>
            <div @click="showInput(index, 'main')" v-if="!item.isShowMainInput" class="main-subject">
              <!-- {{item.main}} -->
              <textarea v-model="item.main"></textarea>
            </div>
            <div class="main-subject" v-if="item.isShowMainInput">
              <!--<input type="text" v-model="item.main" @blur="hideInput(index,'main')" v-focus @keyup="keyupEvents(index,$event,1)">-->
              <textarea v-model="item.main" @blur="hideInput(index, 'main')" v-focus
                @keyup="keyupEvents(index, $event, 1)"></textarea>

              <div class="dropdown-menu suggest-list special-elements" style="top: 60px;">
                <ul class="item-list">
                  <li v-for="main in mainList" v-if="main.name.indexOf(item.main.trim()) != -1"
                    :class="main.name == item.main ? 'hover' : ''" @click="voluationInput(index, 'main', main.name)">{{
                      main.name }}
                  </li>
                </ul>
              </div>

            </div>
            <i v-if="item.isShowMainInput" class="anticon anticon-ellipsis special-elements"
              @click="selectionList(index, 'main')"></i>
          </td>
          <td>
            <div @click="showInput(index, 'subject')" v-if="!item.isShowSubjectInput" class="main-subject">
              <!--{{item.subject}}-->
              <textarea v-model="item.subject.name"></textarea>
            </div>
            <div class="main-subject" v-if="item.isShowSubjectInput">
              <!--<input type="text" v-model="item.subject" @blur="hideInput(index,'subject')" v-focus @keyup="keyupEvents(index,$event,2)">-->
              <textarea v-model="item.subject.name" @blur="hideInput(index, 'subject')" v-focus
                @keyup="keyupEvents(index, $event, 2)"></textarea>

              <div class="dropdown-menu suggest-list special-elements" style="top: 60px;">
                <ul class="item-list">
                  <li v-for="subject in subjectList" v-if="subject.name.indexOf(item.subject.name.trim()) != -1"
                    :class="subject.name == item.subject.name ? 'hover' : ''"
                    @click="voluationInput(index, 'subject', subject)">
                    {{ subject.name }}
                  </li>
                </ul>
              </div>
            </div>
            <i v-if="item.isShowSubjectInput" class="anticon anticon-ellipsis special-elements"
              @click="selectionList(index, 'subject')"></i>
          </td>
          <td v-if="isAuxiliary" :disabled="!item.isAuxiliary" :class="item.isAuxiliary ? '' : 'td-auxiliary-dis'">
            <div class="auxiliary-accounting" v-if="item.isAuxiliary" @click="selectionList(index, 'auxiliary')">
              <div v-if="item.auxiliary && item.auxiliary != ''" class="auxiliary-single">
                <span>{{ item.auxiliary }}</span>
                <i class="el-icon-close" @click.stop="clearAuxiliary(index, $event)"></i>
              </div>
            </div>
          </td>
          <td>
            <table>
              <tr>
                <td width="50%" style="border-right: 1px solid #bab9b9;">
                  <table class="debtor-tbale debtor-lender-table">
                    <tr @click="showInput(index, 'debtor')" v-if="!item.isShowDebtorInput"
                      :class="item.debtor * 1 < 0 ? 'tr-negative' : ''">
                      <td v-for="debtor in item.debtorList">{{ debtor }}</td>
                    </tr>
                    <tr v-if="item.isShowDebtorInput">
                      <input @blur="hideInput(index, 'debtor')" @keyup="debtorInputKeyUp(index, $event, 3)"
                        v-model="item.debtor" maxlength="12" v-focus
                        onkeypress="if((event.keyCode<48 || event.keyCode>57) && event.keyCode!=46 || /\.\d\d$/.test(value))event.returnValue=false">
                    </tr>
                  </table>
                </td>
                <td width="50%">
                  <table class="lender-tbale debtor-lender-table">
                    <tr v-if="!item.isShowLenderInput" @click="showInput(index, 'lender')"
                      :class="item.lender * 1 < 0 ? 'tr-negative' : ''">
                      <td v-for="lender in item.lenderList">{{ lender }}</td>
                    </tr>

                    <tr v-if="item.isShowLenderInput">
                      <input @blur="hideInput(index, 'lender')" @keyup="lenderInputKeyUp(index, $event, 4)"
                        v-model="item.lender" maxlength="11" v-focus
                        onkeypress="if (event.keyCode < 48 || event.keyCode > 57) event.returnValue = false;">
                    </tr>
                  </table>
                </td>
              </tr>
            </table>
          </td>
        </tr>
        <tr>
          <td :colspan="isAuxiliary ? 4 : 2" style="text-align: left;padding-left: 10px;">合计：</td>
          <td style="text-align: left; padding-left: 10px; min-width: 180px; color: #4a90e2;">{{ amountInChinese }}</td>
          <td>
            <table>
              <tr>
                <td width="50%" style="border-right: 1px solid #bab9b9;">
                  <table class="debtor-tbale debtor-lender-table">
                    <tr>
                      <td v-for="debtor in debtorTotalList">{{ debtor }}</td>
                    </tr>
                  </table>
                </td>
                <td width="50%">
                  <table class="lender-tbale debtor-lender-table">
                    <tr>
                      <td v-for="lender in lenderTotalList">{{ lender }}</td>
                    </tr>
                  </table>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
      <div style="height: 50px;line-height: 50px;">制单人：</div>
      <div style="text-align: right;" v-show="saveVisible">
        <a-button @click="preservation(1)">暂存</a-button>
        <a-button type="primary" @click="preservation(2)">保存</a-button>
      </div>
    </div>

    <!--<el-dialog title="摘要列表" width="30%" :visible.sync="dialogMainVisible">
      <main-selector @closeMainDialog="closeMainDialog" ref="mainSelector"></main-selector>
      <span slot="footer" class="dialog-footer">
            <el-button @click="closeMainDialog">取消</el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="edit">确认</el-button>
          </span>
    </el-dialog>
    <el-dialog title="会计科目" width="30%" :visible.sync="dialogSubjectVisible">
      <subject-selector @closeSubjectDialog="closeSubjectDialog" ref="subjectSelector"></subject-selector>
      <span slot="footer" class="dialog-footer">
            <el-button @click="closeSubjectDialog">取消</el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="edit">确认</el-button>
          </span>
    </el-dialog>
    <el-dialog title="请选择" width="30%" :visible.sync="dialogAuxiliaryVisible">
      <auxiliary-selector @closeAuxiliaryDialog="closeAuxiliaryDialog" ref="auxiliarySelector"></auxiliary-selector>
      <span slot="footer" class="dialog-footer">
            <el-button @click="closeAuxiliaryDialog">取消</el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="edit">确认</el-button>
          </span>
    </el-dialog>-->

  </div>
</template>



<script setup>
import { ref, reactive, onMounted, onUpdated, onUnmounted, computed, watch, getCurrentInstance } from 'vue';
import { message, notification } from 'ant-design-vue';
import dayjs from 'dayjs';
// import {
//   addObj,
//   getObj,
//   putObj,
//   getWordList,
//   getMainList,
//   getSubjectList
// } from '@/api';

// 自定义指令 - 自动聚焦
const vFocus = {
  onMounted(el) {
    el.focus();
  }
};
// 注册全局指令
const app = getCurrentInstance().appContext.app;
app.directive('focus', vFocus);
// 定义props
const props = defineProps({
  id: {
    type: [String, Number],
    default: ''
  }
});

// 定义emits
const emits = defineEmits(['submitSuccess']);

// 响应式数据
const voucher = reactive({
  word: '记',
  no: 1,
  date: dayjs(),
  bill: 0
});

const list = ref([
  {
    main: '',
    isShowMainInput: false,
    subject: {
      number: '',
      name: '',
      detailJson: ''
    },
    isShowSubjectInput: false,
    debtor: '',
    debtorList: ['', '', '', '', '', '', '', '', 0, 0, 0],
    isShowDebtorInput: false,
    lender: '',
    lenderList: ['', '', '', '', '', '', '', '', 0, 0, 0],
    isShowLenderInput: false,
    isAuxiliary: false,
    auxiliary: ''
  },
  {
    main: '',
    isShowMainInput: false,
    subject: {
      number: '',
      name: '',
      detailJson: ''
    },
    isShowSubjectInput: false,
    debtor: '',
    debtorList: ['', '', '', '', '', '', '', '', 0, 0, 0],
    isShowDebtorInput: false,
    lender: '',
    lenderList: ['', '', '', '', '', '', '', '', 0, 0, 0],
    isShowLenderInput: false,
    isAuxiliary: false,
    auxiliary: ''
  },
  {
    main: '',
    isShowMainInput: false,
    subject: {
      number: '',
      name: '',
      detailJson: ''
    },
    isShowSubjectInput: false,
    debtor: '',
    debtorList: ['', '', '', '', '', '', '', '', 0, 0, 0],
    isShowDebtorInput: false,
    lender: '',
    lenderList: ['', '', '', '', '', '', '', '', 0, 0, 0],
    isShowLenderInput: false,
    isAuxiliary: false,
    auxiliary: ''
  },
  {
    main: '',
    isShowMainInput: false,
    subject: {
      number: '',
      name: '',
      detailJson: ''
    },
    isShowSubjectInput: false,
    debtor: '',
    debtorList: ['', '', '', '', '', '', '', '', 0, 0, 0],
    isShowDebtorInput: false,
    lender: '',
    lenderList: ['', '', '', '', '', '', '', '', 0, 0, 0],
    isShowLenderInput: false,
    isAuxiliary: false,
    auxiliary: ''
  }
]);

const debtorTotal = ref(0);
const debtorTotalList = ref(['', '', '', '', '', '', '', '', 0, 0, 0]);
const lenderTotal = ref(0);
const lenderTotalList = ref(['', '', '', '', '', '', '', '', 0, 0, 0]);
const wordList = ref([]);
const mainList = ref([]);
const subjectList = ref([]);
const dialogMainVisible = ref(false);
const dialogSubjectVisible = ref(false);
const dialogAuxiliaryVisible = ref(false);
const dialogMainIndex = ref(0);
const dialogSubjectIndex = ref(0);
const dialogAuxiliaryIndex = ref(0);
const isAuxiliary = ref(false);
const saveVisible = ref(true);
const billNo = ref('');
const showTipBox = ref(false);

// 处理键盘事件的函数
const handleEvent = (event) => {
  if (window.location.hash == '#/general_ledger/voucher_entry') {
    if (event.keyCode === 83 && event.ctrlKey) {
      preservation(2);
      event.preventDefault();
      event.returnValue = false;
      return false;
    } else if (event.keyCode === 115) {
      addList();
      event.preventDefault();
      event.returnValue = false;
      return false;
    } else if (event.keyCode === 121) {
      event.preventDefault();
      event.returnValue = false;
      return false;
    } else if (event.keyCode === 122) {
      event.preventDefault();
      event.returnValue = false;
      return false;
    }
  }
};

// // 显示输入框
// const showInput = (index, type) => {
//   console.log('1', index, type);
//   for (let i in list.value) {
//     list.value[i].isShowDebtorInput = false;
//     list.value[i].isShowLenderInput = false;
//     list.value[i].isShowMainInput = false;
//     list.value[i].isShowSubjectInput = false;

//     if (i == index && type == 'debtor') {
//       list.value[index].isShowDebtorInput = true;
//     } else if (i == index && type == 'lender') {
//       list.value[index].isShowLenderInput = true;
//     } else if (i == index && type == 'main') {
//       list.value[index].isShowMainInput = true;
//     } else if (i == index && type == 'subject') {
//       list.value[index].isShowSubjectInput = true;
//     }
//   }
//   console.log('list.value', list.value)
// };
let numzc = ref(1)
// 显示输入框 - 改进版本
const showInput = (index, type) => {
  console.log('触发显示输入框:', index, type);
  numzc.value = numzc.value + 1
  console.log('numzc:', numzc.value);

  // 先重置所有项的输入框状态
  list.value.forEach((item) => {
    item.isShowDebtorInput = false;
    item.isShowLenderInput = false;
    item.isShowMainInput = false;
    item.isShowSubjectInput = false;
  });

  // 只更新目标项的对应输入框状态
  if (type === 'debtor') {
    list.value[index].isShowDebtorInput = true;
  } else if (type === 'lender') {
    list.value[index].isShowLenderInput = true;
  } else if (type === 'main') {
    list.value[index].isShowMainInput = true;
  } else if (type === 'subject') {
    list.value[index].isShowSubjectInput = true;
  }

  console.log('更新后的列表:', list.value);
};


// 隐藏输入框
const hideInput = (index, type) => {
  console.log('失去焦点',)
  if (type == 'debtor') {
    const inx = list.value[index].debtor.indexOf('.');
    if (inx != -1 && list.value[index].debtor.length - 1 != inx) {
      list.value[index].debtor = (list.value[index].debtor * 1).toFixed(4);
    }
    list.value[index].isShowDebtorInput = false;
  } else if (type == 'lender') {
    const inx = list.value[index].lender.indexOf('.');
    if (inx != -1 && list.value[index].lender.length - 1 != inx) {
      list.value[index].lender = (list.value[index].lender * 1).toFixed(4);
    }
    list.value[index].isShowLenderInput = false;
  } else if (type == 'main') {
    list.value[index].isShowMainInput = false;
  } else if (type == 'subject') {
    list.value[index].isShowSubjectInput = false;
  }
};

// 更新输入值
const voluationInput = (index, type, val) => {
  if (type == 'main') {
    list.value[index].main = val;
    list.value[index].isShowMainInput = false;
  } else if (type == 'subject') {
    list.value[index].subject.number = val.number;
    list.value[index].subject.name = val.name;
    list.value[index].subject.detailJson = val.detailJson;
    list.value[index].isShowSubjectInput = false;
  }
  judgeIsAuxiliary();
};

// 判断是否需要辅助核算
const judgeIsAuxiliary = () => {
  let flag = false;
  for (let i in list.value) {
    const detailJson = list.value[i].subject.detailJson;
    if (detailJson !== '' && detailJson !== undefined) {
      flag = true;
      list.value[i].isAuxiliary = true;
    } else {
      list.value[i].isAuxiliary = false;
      list.value[i].auxiliary = '';
    }
  }
  isAuxiliary.value = flag;
};

// 打开主对话框
const openMainDialog = () => {
  dialogMainVisible.value = true;
};

// 关闭主对话框
const closeMainDialog = (main) => {
  if (!main.isTrusted) {
    list.value[dialogMainIndex.value].main = main;
  }
  dialogMainVisible.value = false;
};

// 打开科目对话框
const openSubjectDialog = () => {
  dialogSubjectVisible.value = true;
};

// 关闭科目对话框
const closeSubjectDialog = (sub) => {
  if (!sub.isTrusted) {
    list.value[dialogSubjectIndex.value].subject = sub;
  }
  dialogSubjectVisible.value = false;
  judgeIsAuxiliary();
};

// 打开辅助核算对话框
const openAuxiliaryDialog = () => {
  dialogAuxiliaryVisible.value = true;
};

// 关闭辅助核算对话框
const closeAuxiliaryDialog = (aux) => {
  if (!aux.isTrusted) {
    list.value[dialogAuxiliaryIndex.value].auxiliary = aux;
  }
  dialogAuxiliaryVisible.value = false;
};

// 清除辅助核算
const clearAuxiliary = (index, e) => {
  list.value[index].auxiliary = '';
};

// 选择列表
const selectionList = (index, type) => {
  if (type == 'main') {
    dialogMainIndex.value = index;
    openMainDialog();
  } else if (type == 'subject') {
    dialogSubjectIndex.value = index;
    openSubjectDialog();
  } else if (type == 'auxiliary') {
    dialogAuxiliaryIndex.value = index;
    openAuxiliaryDialog();
  }
};

// 键盘事件处理
const keyupEvents = (index, e, remaind) => {
  if (e.keyCode == 37) {
    keyboardEvents('left', index * 4 + remaind);
    return;
  } else if (e.keyCode == 38) {
    keyboardEvents('up', index * 4 + remaind);
    return;
  } else if (e.keyCode == 39) {
    keyboardEvents('right', index * 4 + remaind);
    return;
  } else if (e.keyCode == 40) {
    keyboardEvents('down', index * 4 + remaind);
    return;
  } else if (e.keyCode == 13) {
    keyboardEvents('enter', index * 4 + remaind);
    return;
  } else if (e.keyCode == 118) {
    if (remaind == 1) {
      selectionList(index, 'main');
    } else if (remaind == 2) {
      selectionList(index, 'subject');
    }
    return;
  }

  const main = list.value[index].main;
  const subject = list.value[index].subject.name;
  if (index - 1 >= 0) {
    if (main.indexOf('//') != -1 || subject.indexOf('//') != -1) {
      list.value[index].main = list.value[index - 1].main;
      list.value[index].subject = list.value[index - 1].subject;
      list.value[index].debtor = list.value[index - 1].debtor;
      list.value[index].debtorList = list.value[index - 1].debtorList;
      list.value[index].lender = list.value[index - 1].lender;
      list.value[index].lenderList = list.value[index - 1].lenderList;
      list.value[index].auxiliary = list.value[index - 1].auxiliary;
      calcDebtorTotal();
      calcLenderTotal();
    }
    if (main.indexOf('..') != -1) {
      list.value[index].main = list.value[index - 1].main;
    }
  }
  judgeIsAuxiliary();
};

// 键盘导航
const keyboardEvents = (type, number) => {
  const total = list.value.length * 4;
  if (type == 'enter') {
    number++;
  } else if (type == 'left' && number - 1 > 0) {
    number--;
  } else if (type == 'right' && number + 1 <= total) {
    number++;
  } else if (type == 'up' && number - 4 > 0) {
    number = number - 4;
  } else if (type == 'down' && number + 4 <= total) {
    number = number + 4;
  }
  if (type == 'enter' && number > total) {
    addList();
  }
  const index = parseInt(number / 4);
  const remaind = number % 4;
  if (remaind == 1) {
    showInput(index, 'main');
  } else if (remaind == 2) {
    showInput(index, 'subject');
  } else if (remaind == 3) {
    showInput(index, 'debtor');
  } else if (remaind == 0) {
    showInput(index - 1, 'lender');
  }
};

// 借方金额输入事件
const debtorInputKeyUp = (index, e, remaind) => {
  if (e.keyCode === 187) {
    calcDebtorTotal(index);
    calcLenderTotal(index);
    let cha = lenderTotal.value - debtorTotal.value;

    if (cha == 0) {
      cha = '';
    }
    list.value[index].debtor = cha + '';
  } else if (e.keyCode === 32) {
    list.value[index].isShowLenderInput = true;
    list.value[index].isShowDebtorInput = false;
    list.value[index].lender = list.value[index].debtor.trim();
    list.value[index].debtor = '';
    list.value[index].debtorList = ['', '', '', '', '', '', '', '', 0, 0, 0];
    const lenderList = ['', '', '', '', '', '', '', '', 0, 0, 0];
    list.value[index].lenderList = collatingData(list.value[index].lender, lenderList);
    calcDebtorTotal();
    calcLenderTotal();
    return;
  } else if ((e.keyCode >= 37 && e.keyCode <= 40) || e.keyCode == 13) {
    keyupEvents(index, e, remaind);
    return;
  }
  list.value[index].lender = '';
  list.value[index].lenderList = ['', '', '', '', '', '', '', '', 0, 0, 0];
  const debtor = list.value[index].debtor;
  const debtorList = ['', '', '', '', '', '', '', '', 0, 0, 0];
  list.value[index].debtorList = collatingData(debtor, debtorList);
  calcDebtorTotal();
  calcLenderTotal();
};

// 计算借方总额
const calcDebtorTotal = (index) => {
  let total = 0;
  for (let i in list.value) {
    if (list.value[i].debtor != null && list.value[i].debtor != '') {
      if (!(index && index == i)) {
        total += (list.value[i].debtor) * 1;
      }
    }
  }
  debtorTotal.value = total;
  const totalStr = total + '';
  const listData = ['', '', '', '', '', '', '', '', 0, 0, 0];
  debtorTotalList.value = collatingData(totalStr, listData);
};

// 贷方金额输入事件
const lenderInputKeyUp = (index, e, remaind) => {
  if (e.keyCode === 187) {
    calcDebtorTotal(index);
    calcLenderTotal(index);
    let cha = debtorTotal.value - lenderTotal.value;
    if (cha == 0) {
      cha = '';
    }
    list.value[index].lender = cha + '';
  } else if (e.keyCode === 32) {
    list.value[index].isShowDebtorInput = true;
    list.value[index].isShowLenderInput = false;
    list.value[index].debtor = list.value[index].lender.trim();
    list.value[index].lender = '';
    list.value[index].lenderList = ['', '', '', '', '', '', '', '', 0, 0, 0];
    const debtorList = ['', '', '', '', '', '', '', '', 0, 0, 0];
    list.value[index].debtorList = collatingData(list.value[index].debtor, debtorList);
    calcLenderTotal();
    calcDebtorTotal();
    return;
  } else if ((e.keyCode >= 37 && e.keyCode <= 40) || e.keyCode == 13) {
    keyupEvents(index, e, remaind);
    return;
  }
  list.value[index].debtor = '';
  list.value[index].debtorList = ['', '', '', '', '', '', '', '', 0, 0, 0];
  const lender = list.value[index].lender;
  const lenderList = ['', '', '', '', '', '', '', '', 0, 0, 0];
  list.value[index].lenderList = collatingData(lender, lenderList);
  calcLenderTotal();
  calcDebtorTotal();
};

// 计算贷方总额
const calcLenderTotal = (index) => {
  let total = 0;
  for (let i in list.value) {
    if (list.value[i].lender != null && list.value[i].lender != '') {
      if (!(index && index == i)) {
        total += (list.value[i].lender) * 1;
      }
    }
  }
  lenderTotal.value = total;
  const totalStr = total + '';
  const listData = ['', '', '', '', '', '', '', '', 0, 0, 0];
  lenderTotalList.value = collatingData(totalStr, listData);
};

// 添加一行
const addList = () => {
  const obj = {
    main: '',
    isShowMainInput: false,
    subject: {
      number: '',
      name: '',
      detailJson: ''
    },
    isShowSubjectInput: false,
    debtor: '',
    debtorList: ['', '', '', '', '', '', '', '', 0, 0, 0],
    isShowDebtorInput: false,
    lender: '',
    lenderList: ['', '', '', '', '', '', '', '', 0, 0, 0],
    isShowLenderInput: false,
    isAuxiliary: false,
    auxiliary: ''
  };
  list.value.push(obj);
};

// 删除一行
const removeList = (index) => {
  if (list.value.length <= 2) {
    message.error('至少保存两行');
    return;
  }
  list.value.splice(index, 1);
  calcDebtorTotal();
  calcLenderTotal();
};

// 整理数据格式
const collatingData = (value, list) => {
  value = value.replace(/-/g, '');
  if (value.indexOf('.') != -1) {
    value = (value * 1).toFixed(4);
    value = (value + '').replace(/\./g, '');
  } else {
    value = value + '00';
  }
  if (value.length <= 11) {
    const cha = list.length - value.length;
    for (let i = 0; i < value.length; i++) {
      list[i + cha] = value.charAt(i);
    }
  } else {
    for (let i = 0; i < value.length; i++) {
      list[i] = value.charAt(i);
    }
  }
  return list;
};

// 检查数据
const checkListData = () => {
  if ((debtorTotal.value != 0 || lenderTotal.value != 0) && lenderTotal.value * 1 != debtorTotal.value * 1) {
    message.error('凭证借贷不平衡，请检查');
    return;
  }
  let mainFlag = true;
  for (let i in list.value) {
    console.log('list.value[i]', list.value[i]);
    if (list.value[i].main != null && list.value[i].main != '') {
      mainFlag = false;
    }
    if (list.value[i].subject.name == null || list.value[i].subject.name == '') {
      message.error('第' + (i * 1 + 1) + '行中的会计科目为必填项，请填写了再提交');
      return;
    }
    if ((list.value[i].debtor == null || list.value[i].debtor == '') && (list.value[i].lender == null || list.value[i].lender == '')) {
      message.error('第' + (i * 1 + 1) + '行中借方金额、贷方金额必须填一个，请填写了再提交');
      return;
    }
  }
  if (mainFlag) {
    message.error('必须填写一个摘要，请填写了再提交');
    return;
  }

  const dataList = [];
  for (let a = 0; a < list.value.length; a++) {
    const obj = {
      explanation: list.value[a].main,
      accountNumber: list.value[a].subject.number,
      accountName: list.value[a].subject.name,
      auxiliaryType: list.value[a].subject.detailJson,
      itemObjectKeys: list.value[a].auxiliary,
      basicDebitAmount: list.value[a].debtor,
      basicCreditAmount: list.value[a].lender
    };
    dataList.push(obj);
  }
  const reqObj = {
    id: props.id,
    billNo: billNo.value,
    billStatus: 2,
    voucherType: voucher.word,
    voucherNumber: voucher.no,
    year: formatDate("yyyy-MM-dd hh:mm:ss", voucher.date),
    creditTotal: lenderTotal.value,
    debitTotal: debtorTotal.value,
    attachments: voucher.bill,
    list: dataList
  };

  return reqObj;
};

// 格式化日期
const formatDate = (fmt, date) => {
  if (!date) return '';
  // dayjs 格式兼容
  fmt = fmt.replace('yyyy', 'YYYY').replace('dd', 'DD').replace('hh', 'HH');
  if (typeof date.format === 'function') {
    return date.format(fmt);
  }
  return dayjs(date).format(fmt);
};

// 保存数据
const preservation = (status) => {
  const reqObj = checkListData();

  if (reqObj) {
    addObj(reqObj).then(response => {
      if (response.code == '2000') {
        notification.success({
          message: '成功',
          description: '创建成功',
          duration: 2
        });
        init();
      } else {
        notification.warning({
          message: '失败',
          description: response.msg,
          duration: 2
        });
      }
    });
  }
};

// 提交数据
const onSubmit = () => {
  const reqObj = checkListData();

  if (reqObj) {
    putObj(props.id, reqObj).then(response => {
      if (response.code == '2000') {
        notification.success({
          message: '成功',
          description: '修改成功',
          duration: 2
        });
        emits('submitSuccess', response);
      } else {
        notification.warning({
          message: '失败',
          description: response.msg,
          duration: 2
        });
      }
    });
  }
};

// 初始化数据
const init = () => {
  if (props.id !== '' && props.id !== undefined) {
    getObj(props.id)
      .then(response => {
        const data = response.data;
        voucher.word = data.voucherType;
        voucher.no = data.voucherNumber;
        voucher.date = dayjs(data.year);
        voucher.bill = data.attachments;
        list.value.splice(0, list.value.length); // 清空数组
        let hasAuxiliary = false;
        for (let i = 0; i < data.list.length; i++) {
          const debtor = data.list[i].basicDebitAmount == 0 ? '' : data.list[i].basicDebitAmount + '';
          const debtorList = debtor == '' ? ['', '', '', '', '', '', '', '', 0, 0, 0] : collatingData(debtor, ['', '', '', '', '', '', '', '', 0, 0, 0]);
          const lender = data.list[i].basicCreditAmount == 0 ? '' : data.list[i].basicCreditAmount + '';
          const lenderList = lender == '' ? ['', '', '', '', '', '', '', '', 0, 0, 0] : collatingData(lender, ['', '', '', '', '', '', '', '', 0, 0, 0]);
          if (data.list[i].itemObjectKeys != null && data.list[i].itemObjectKeys != '') {
            hasAuxiliary = true;
          }
          const obj = {
            main: data.list[i].explanation,
            isShowMainInput: false,
            subject: {
              number: data.list[i].accountNumber,
              name: data.list[i].accountName,
              detailJson: data.list[i].auxiliaryType
            },
            isShowSubjectInput: false,
            debtor: debtor,
            debtorList: debtorList,
            isShowDebtorInput: false,
            lender: lender,
            lenderList: lenderList,
            isShowLenderInput: false,
            isAuxiliary: data.list[i].itemObjectKeys == '' ? false : true,
            auxiliary: data.list[i].itemObjectKeys
          };
          list.value.push(obj);
        }
        debtorTotal.value = data.debitTotal + '';
        debtorTotalList.value = collatingData(debtorTotal.value, ['', '', '', '', '', '', '', '', 0, 0, 0]);
        lenderTotal.value = data.creditTotal + '';
        lenderTotalList.value = collatingData(lenderTotal.value, ['', '', '', '', '', '', '', '', 0, 0, 0]);
        dialogMainVisible.value = false;
        dialogSubjectVisible.value = false;
        dialogAuxiliaryVisible.value = false;
        saveVisible.value = false;
        dialogMainIndex.value = 0;
        dialogSubjectIndex.value = 0;
        dialogAuxiliaryIndex.value = 0;
        isAuxiliary.value = hasAuxiliary;
        billNo.value = data.billNo;
      });
  } else {
    voucher.word = '记';
    voucher.no = 1;
    voucher.date = dayjs();
    voucher.bill = 0;
    list.value.splice(0, list.value.length); // 清空数组
    // 添加4个空行
    for (let i = 0; i < 4; i++) {
      list.value.push({
        main: '',
        isShowMainInput: false,
        subject: {
          number: '',
          name: '',
          detailJson: ''
        },
        isShowSubjectInput: false,
        debtor: '',
        debtorList: ['', '', '', '', '', '', '', '', 0, 0, 0],
        isShowDebtorInput: false,
        lender: '',
        lenderList: ['', '', '', '', '', '', '', '', 0, 0, 0],
        isShowLenderInput: false,
        isAuxiliary: false,
        auxiliary: ''
      });
    }
    debtorTotal.value = 0;
    debtorTotalList.value = ['', '', '', '', '', '', '', '', 0, 0, 0];
    lenderTotal.value = 0;
    lenderTotalList.value = ['', '', '', '', '', '', '', '', 0, 0, 0];
    dialogMainVisible.value = false;
    dialogSubjectVisible.value = false;
    dialogAuxiliaryVisible.value = false;
    dialogMainIndex.value = 0;
    dialogSubjectIndex.value = 0;
    dialogAuxiliaryIndex.value = 0;
    isAuxiliary.value = false;
  }
};

// 金额转中文大写
function numberToChinese(n) {
  if (n === undefined || n === null || n === '') return '';
  n = Number(n);
  if (isNaN(n)) return '';
  const fraction = ['角', '分', '毫', '厘'];
  const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  const unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
  let head = n < 0 ? '负' : '';
  n = Math.abs(n);
  let s = '';
  for (let i = 0; i < fraction.length; i++) {
    s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
  }
  s = s || '整';
  n = Math.floor(n);
  for (let i = 0; i < unit[0].length && n > 0; i++) {
    let p = '';
    for (let j = 0; j < unit[1].length && n > 0; j++) {
      p = digit[n % 10] + unit[1][j] + p;
      n = Math.floor(n / 10);
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
  }
  return head + s.replace(/(零.)*零元/, '元')
    .replace(/(零.)+/g, '零')
    .replace(/^整$/, '零元整');
}

// 计算属性：借方总额中文大写
const amountInChinese = computed(() => numberToChinese(debtorTotal.value));

// 生命周期钩子
onMounted(() => {
  document.addEventListener('keydown', handleEvent);
  // getWordList().then(response => {
  //   wordList.value = response.data.records;
  // });
  // getMainList().then(response => {
  //   mainList.value = response.data.records;
  // });
  // getSubjectList().then(response => {
  //   subjectList.value = response.data.records;
  // });

  init();
});

onUpdated(() => {
  const chargeContainer = document.getElementById('chargeContainer');
  if (chargeContainer) {
    const outDiv = chargeContainer.getElementsByClassName('special-elements');
    for (let i = 0; i < outDiv.length; i++) {
      outDiv[i].onmousedown = function (e) {
        if (e && e.preventDefault)
          e.preventDefault();
        else
          window.event.returnValue = false;
        return false;
      }
    }
  }
});

onUnmounted(() => {
  document.removeEventListener('keydown', handleEvent);
});

</script>


<style scoped>
table {
  width: 100%;
  border-spacing: 0;
  border-collapse: collapse;
  padding: 0;
  margin: 0;
}

table td {
  text-align: center;
  table-layout: fixed;
  padding: 0px;
  position: relative;
}

.main-subject {
  position: relative;
  height: 60px;
  line-height: 30px;
  text-align: left;
}

.charge-container {
  padding: 10px;
  font-size: 14px;
  color: #444;
  font-weight: 400;
  background-color: white;
}

.charge {
  width: 1124px;
  margin: auto;
}

.charge-header {
  margin-bottom: 10px;
}

.charge-header>div {
  display: inline-block;
  margin-right: 15px;
}

.tip-box {
  width: 330px;
  padding: 10px;
  position: absolute;
  top: 27px;
  right: -15px;
  z-index: 1005;
  background-color: #fff;
  box-shadow: 0 0 6px rgba(170, 170, 170, .73);
  display: none;
}

.tip-box-table tr {
  height: 25px;
}

.el-icon-info {
  font-size: 18px;
  margin-left: 30px;
  cursor: pointer;
}

.el-icon-info:hover+.tip-box {
  display: inline-block;
}

.el-icon-more {
  position: absolute;
  top: 22px;
  right: 10px;
  z-index: 2;
  color: #666;
  cursor: pointer;
  font-size: 16px;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0px;
  float: left;
  padding: 5px 0;
  margin: 2px 0 0;
  text-align: left;
  list-style: none;
  background-color: #fff;
  background-clip: padding-box;
}

.suggest-list {
  width: 100%;
  height: auto;
  z-index: 1015;
  min-width: inherit;
  display: block;
  overflow: hidden;
  border: none;
  box-shadow: 0 1px 6px rgba(0, 0, 0, .2);
}

.suggest-list .item-list {
  max-height: 375px;
  overflow: auto;
  list-style: none;
  margin: 0px;
  padding: 0px;
}

.item-list li {
  display: flex;
  padding: 0 10px;
  height: 28px;
  line-height: 28px;
  cursor: pointer;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.item-list li:hover {
  background: #ecebeb;
}

.item-list li.hover {
  background: #ecebeb;
}

.charge-table,
.tip-box-table {
  border: 1px solid #bab9b9;
}

.charge-table,
.debtor-tbale,
.lender-tbale>tr {
  height: 60px;
}

.charge-table>tr:first-child {
  height: 50px;
}

.td-auxiliary-dis {
  background-color: #f7f7f7;
}

.auxiliary-accounting {
  height: 60px;
  overflow: auto;
  padding: 15px 0 0 30px;
}

.auxiliary-accounting:before {
  content: "+";
  font-size: 30px;
  color: #4a90e2;
  cursor: pointer;
  padding: 0 11px;
  position: absolute;
  top: 0;
  left: 0;
  line-height: 60px;
}

.auxiliary-single {
  display: flex;
  float: left;
  height: 28px;
  line-height: 28px;
  margin-right: 5px;
  cursor: pointer;
  background: #eee;
  padding: 0 8px;
  border-radius: 2px;
}

.auxiliary-single span {
  max-width: 90px;
  overflow: hidden;
  height: 28px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.auxiliary-single i {
  color: red;
  margin: 8px 0 8px 7px;
  font-size: 10px;
  visibility: hidden;
}

.auxiliary-single:hover i {
  visibility: inherit;
}

.charge-table-icon {
  cursor: pointer;
  display: inline-block;
}

.debtor-lender-table tr td {
  width: 9%;
  border-right: 1px solid #bab9b9;
}

.debtor-lender-table tr td:nth-child(3) {
  border-right-color: rgba(74, 144, 226, .5);
}

.debtor-lender-table tr td:nth-child(6) {
  border-right-color: rgba(74, 144, 226, .5);
}

.debtor-lender-table tr td:nth-child(9) {
  border-right-color: rgba(226, 106, 74, .5);
}

.debtor-lender-table tr td:last-child {
  border-right: none;
}

.tr-negative {
  color: red;
}

.charge-table input,
select {
  width: 100%;
  height: 60px;
}

.charge-table textarea {
  width: 100%;
  height: 60px;
  padding: 9px 14px 9px 10px;
  overflow: auto;
  resize: none;
  border: none;
  border-radius: 0px;
  margin: 0;
  color: #444;
  box-sizing: border-box;
}
</style>